package com.sentinel.demo.push.nacos.init;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sentinel.demo.common.SpringBeanUtils;
import com.sentinel.demo.push.nacos.config.SentinelConfig;

import java.util.List;

/**
 * @author dsy on 2019/12/9
 */
public class NacosDataSourceInit implements InitFunc {
    @Override
    public void init() throws Exception {
        final String remoteAddress = SpringBeanUtils.getBean(SentinelConfig.class).getNacosServerAddr();
        final String groupId = SpringBeanUtils.getBean(SentinelConfig.class).getNacosGroupId();
        final String dataId = SpringBeanUtils.getBean(SentinelConfig.class).getNacosDtaId();

        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(remoteAddress, groupId, dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }
}
